package com.mew.lobby.handler.gameconf;

import com.mew.common.dc.redis.GameRoomRedisService;
import com.mew.common.entity.config.Game;
import com.mew.common.exception.ResponseCode;
import com.mew.common.rest.bo.MewSession;
import com.mew.lobby.annotation.LobbyHandler;
import com.mew.lobby.message.response.GameInfoMessage;
import com.mew.lobby.message.response.GameListResponseMessage;
import com.mew.lobby.net.LobbyHandlerMapCmdType;
import com.mew.lobby.net.MewHandler;
import com.zebra.remoting.config.EmptyMessage;
import com.zebra.remoting.config.StateMessage;
import com.zebra.remoting.protocol.ZebraCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author King.Song
 * @Date 2020/11/14 0014
 **/
@Service
@Slf4j
@LobbyHandler(LobbyHandlerMapCmdType.GameList)
public class LoadGameListHandler implements MewHandler<EmptyMessage> {

    @Autowired
    private GameRoomRedisService gameRoomRedisService;

    @Override
    public void handle(ZebraCommand<EmptyMessage> zebraCommand, MewSession session) {
        List<Game> list = gameRoomRedisService.findAllGame();
        if (null == list || list.isEmpty()){
            zebraCommand.sendMessage( StateMessage.builder().state(ResponseCode.GameServerNotConfig.code()).build());
            return;
        }

        List<GameInfoMessage> gameList = new ArrayList<>(list.size());
        list.stream().sorted((o1, o2) -> o1.getGameSeq().compareTo(o2.getGameSeq())).forEach( g ->  gameList.add(new GameInfoMessage().buildData(g)));
        zebraCommand.sendMessage(GameListResponseMessage.builder().list(gameList).build());
    }
}
